<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/7/5
 * Time: 9:33
 */

namespace app\jiaxiaotong\controller;


use cmf\controller\BaseController;

class TestController extends  BaseController
{
    public function index()
    {
        //获得参数signture nonce toke timestamp
        $signature=$this->request->get('$signature');
        $nonce=$this->request->get('nonce');
        $token='imooc';
        $timestamp=$this->request->get('timestamp');
        $echostr=$this->request->get('echostr');
        $array=array($nonce,$timestamp,$token);
        sort($array);
        $str=sha1(implode($array));
        if($signature==$str && $echostr)
        {
            /*
           * 第一个接入微信的api，api接口的时候，第二次验证就少了$echostr
           */
            echo $echostr;
        }else{
                /*
              * 第一个接入微信的api，api接口的时候，第二次验证就少了$echostr,直接推送
              */
            $this->responseMsg();
        }

    }

    /*
     * 接收事件的推送并回复
     */
    public function responseMsg()
    {
        //1.微信推送的的数据 xml格式
        $postArr=$GLOBALS['HTTP_RAW_POST_DATA'];
        //2.处理消息类型，并设置回复类型和内容
        /*
         * <xml>
        <ToUserName><![CDATA[toUser]]></ToUserName>
        <FromUserName><![CDATA[FromUser]]></FromUserName>
        <CreateTime>123456789</CreateTime>
        <MsgType><![CDATA[event]]></MsgType>
        <Event><![CDATA[subscribe]]></Event>
        </xml>
         */
        $postObj=simplexml_load_string($postArr);
//        $postObj->ToUsername='';
//        $postObj->FromUserName=''; //发送者
//        $postObj->CreateTime='';
//        $postObj->MsgType='';
//        $postObj->Event='';
        //处理消息 该数据包是否订阅推送
        if(strtolower($postObj->MsgType=='event'))
        {

            //如果是关注subscribe事件
            if(strtolower($postObj->Event=='subscribe'))
            {
                //回复用户消息
                //接受者
                $toUser=$postObj->FromUserName;
                $fromUser=$postObj->ToUsername;
                $time=time();
                $msgType='text';
                $content='欢迎关注微信号';
                /*
                 * <xml>
                <ToUserName><![CDATA[toUser]]></ToUserName>
                <FromUserName><![CDATA[fromUser]]></FromUserName>
                <CreateTime>12345678</CreateTime>
                <MsgType><![CDATA[text]]></MsgType>
                <Content><![CDATA[你好]]></Content>
                </xml>
                 */
                $template="<xml>
                <ToUserName><![CDATA[%s]]></ToUserName>
                <FromUserName><![CDATA[%s]]></FromUserName>
                <CreateTime>%s</CreateTime>
                <MsgType><![CDATA[%s]]></MsgType>
                <Content><![CDATA[%s]]></Content>
                </xml>";
                //
               $info=sprintf($template,$toUser,$fromUser,$time,$msgType,$content);
            }
        }

        //3.回复文本消息
        if(strtolower($postObj->MsgType=='text'))
        {
            switch(trim($postObj->content))
            {
                case 1:
                    $content = '您输入的数字是1';
                    break;
                case 2:
                    $content = '您输入的数字是2';
                    break;
                case 3:
                    $content = '您输入的数字是3';
                    break;
                case 4:
                    $content = "<a href='http://www.imooc.com'>慕课</a>";
                    break;
                case '英文':
                    $content = 'imooc is ok';
                    break;

            }
                $template = "<xml>
                <ToUserName><![CDATA[%s]]></ToUserName>
                <FromUserName><![CDATA[%s]]></FromUserName>
                <CreateTime>%s</CreateTime>
                <MsgType><![CDATA[%s]]></MsgType>
                <Content><![CDATA[%s]]></Content>
                </xml>";
                $fromUser = $postObj->ToUserName;
                $toUser   = $postObj->FromUserName;
                $time     = time();
                // $content  = '18723180099';
                $msgType  = 'text';
                echo sprintf($template, $toUser, $fromUser, $time, $msgType, $content);

        }
        //4.回复图文消息 用户回复图文关键字
        if(strtolower($postObj->MsgType=='text') && trim($postObj->content='tuwen1'))
        {
                $toUser=$postObj->FromUserName;
                $fromUser=$postObj->ToUserName;
            $arr=array(
                array( 'title'=>'imooc',
                    'Description'=>'imooc is very good',
                    'PicUrl'=>'http:/www/img',
                    'url'=>'http://www.baidu.com',
                    ),
                array( 'title'=>'imooc1',
                    'Description'=>'imooc is very good',
                    'PicUrl'=>'http:/www/img',
                    'url'=>'http://www.baidu.com',
                ),
                array( 'title'=>'imooc2',
                    'Description'=>'imooc is very good3',
                    'PicUrl'=>'http:/www/img',
                    'url'=>'http://www.baidu.com',
                ),
            );
               $template="
               <xml>
                <ToUserName><![CDATA[toUser]]></ToUserName>
                <FromUserName><![CDATA[fromUser]]></FromUserName>
                <CreateTime>12345678</CreateTime>
                <MsgType><![CDATA[news]]></MsgType>
                <ArticleCount>".count($arr)."</ArticleCount>
                <Articles>";
            foreach($arr as $k=>$v)
            {
                $template.="<item>
                <Title><![CDATA[".$v['title']."]]></Title>
                <Description><![CDATA[description1]]></Description>
                <PicUrl><![CDATA[picurl]]></PicUrl>
                <Url><![CDATA[url]]></Url>
                </item>";
            }

               $template.="</Articles>
                </xml>";

            echo sprintf($template,$fromUser,$toUser,time(),'news');

        }







    }
    /*
     * 微信接口2000次，从缓存去获取，时间过期了，重新获取，全局缓存调用
     */
    public function http_curl()
    {
        //获取
        //1.初始化
        $ch=curl_init();
        $url='';
        //设置参数
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        //采集
        curl_exec($ch);
        if(curl_errno($ch))
        {
            dump(curl_error());
        }
        //关闭
        curl_close($ch);
    }
    /*
     * 微信 access_token
     */
    public function getWXAccessToken()
    {
        //请求url地址
        $appid='wx1212';
        $appsecret='';
        $url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appsecret";
        $ch=curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        $res=curl_exec($ch);
        if(curl_errno($ch))
        {
            dump(curl_error($ch));
        }
        $arr=json_decode($res,true);
    }
  /*
   * 微信的服务器
   */
    public function getWXServerIp()
    {
        $accesstoken='';
        $url='https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token=$accesstoken';
        $ch=curl_init();
        curl_setopt($ch,CURLOPT_URL);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        $res=curl_exec($ch);
        curl_close();
        if(curl_errno($ch))
        {
            dump(curl_error($ch));
        }
        return json_decode($res,true);
    }
    /*
     *test
     */
    public function test()
    {
        // http_build-query
        //parse_url
        //html_entity_decode
        //HTTP_RAW_POST_DATA
        //array_replace
        //parse_str
        dump($_SERVER['HTTP_HOST']."/public/upload");
        dump($_SERVER['CONTEXT_DOCUMENT_ROOT']);
        /*
        $url = 'http://username:password@hostname/path?arg=value&name=shan#anchor';
        dump(parse_url($url));
        dump($a=parse_url($url,PHP_URL_QUERY));
        dump(html_entity_decode($a));
        parse_str(html_entity_decode($a),$b);
        dump(http_build_query($b));
        $a=[1,2];
        dump(array_merge($a,$b));
        dump(strpos($url,"?"));
        //第一次出现之前的strstr（true)
//        string(38) "http://username:password@hostname/path"
//        string(27) "?arg=value&name=shan#anchor"
        dump(strpos($url,"?")?strstr($url,"?",true):1);
        dump(strpos($url,"?")?strstr($url,"?"):1);
        dump(PHP_OS);
        dump(DIRECTORY_SEPARATOR);
        dump(microtime(true));
        dump(microtime());
        dump($_FILES);
        dump($_SERVER['SCRIPT_FILENAME']);
        dump($aa=dirname($_SERVER['SCRIPT_FILENAME']));
        dump($cc=dirname(realpath($_SERVER['SCRIPT_FILENAME'])));
        // 注意 \\ \/
        $preg='/\d/';
        $arr = array(11,2,'abc','d',3,4,'5b');
        $result=preg_replace($preg,'*',$arr);

        $str='1323fsr12';
        dump($result);
        dump($arr_split=preg_match($preg,$str,$arr2));
        dump($arr2);

        dump(preg_split($preg,$str));

        dump($arr1=preg_grep($preg,$arr));
        dump($arr1);

        dump(str_replace('\\','/',$cc));
        dump(str_replace('/','||',$aa));




//        float(1499246883.9907)
//      string(21) "0.99071900 1499246883"
        dump(array_replace($a,$b));
        dump($b);
        */
    }
}